package com.boatAnchorAssistant.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boatAnchorAssistant.pojo.entity.*;
import com.boatAnchorAssistant.pojo.param.userCollect.*;
import com.boatAnchorAssistant.pojo.vo.userCollect.*;
import com.boatAnchorAssistant.pojo.dto.userCollect.*;
import com.boatAnchorAssistant.service.repository.in.DataDictionaryRepository;
import com.boatAnchorAssistant.service.repository.in.DeviceRepository;
import com.boatAnchorAssistant.service.repository.in.UserCollectRepository;
import com.boatAnchorAssistant.service.repository.in.UserRepository;
import com.boatAnchorAssistant.service.service.in.UserCollectService;
import nirvana.core.context.WebContext;
import nirvana.core.domains.vo.PageResult;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：我的收藏服务
 * 【环 境】：J2SE 17
 * 【详 细】：
 */
@Service
public class UserCollectServiceImpl implements UserCollectService {

    private final UserCollectRepository userCollectRepository;
    private final DeviceRepository deviceRepository;
    private final UserRepository userRepository;
    private final DataDictionaryRepository dataDictionaryRepository;

    public UserCollectServiceImpl(UserCollectRepository userCollectRepository, DeviceRepository deviceRepository, UserRepository userRepository, DataDictionaryRepository dataDictionaryRepository) {
        this.userCollectRepository = userCollectRepository;
        this.deviceRepository = deviceRepository;
        this.userRepository = userRepository;
        this.dataDictionaryRepository = dataDictionaryRepository;
    }


    /**
     * 创建我的收藏
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createUserCollect(CreateUserCollectParam param) {
        //先删除之前的收藏
        Long userId = WebContext.getCurrentUserId();
        List<UserCollect> userCollectListByUserId = getUserCollectListByUserId(userId);
        if (CollectionUtil.isNotEmpty(userCollectListByUserId)) {
            List<Long> ids = userCollectListByUserId.stream().map(UserCollect::getId).collect(Collectors.toList());
            userCollectRepository.removeBatchByIds(ids);
        }

        List<Long> deviceIds = param.getDeviceIds();
        if (CollectionUtil.isNotEmpty(deviceIds)) {
            for (Long deviceId : deviceIds) {
                UserCollect userCollect = new UserCollect();
                BeanUtils.copyProperties(param, userCollect);
                Long id = IdGenerator.SNOW.generate();
                userCollect.setId(id);
                userCollect.setUserId(userId);
                userCollect.setDeviceId(deviceId);
                userCollectRepository.create(userCollect);
            }
        }
    }

    private List<UserCollect> getUserCollectListByUserId(Long userId) {
        UserCollect userCollect = new UserCollect();
        userCollect.setUserId(userId);
        userCollect.setIsDelete(false);

        List<UserCollect> listByEntity = userCollectRepository.getListByEntity(userCollect);
        return listByEntity;
    }

    /**
     * 修改我的收藏
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editUserCollect(EditUserCollectParam param) {
        //先删除之前的收藏
        Long userId = WebContext.getCurrentUserId();
        List<UserCollect> userCollectListByUserId = getUserCollectListByUserId(userId);
        if (CollectionUtil.isNotEmpty(userCollectListByUserId)) {
            List<Long> ids = userCollectListByUserId.stream().map(UserCollect::getId).collect(Collectors.toList());
            if (!userCollectRepository.removeBatchByIds(ids)) {
                throw new RuntimeException("处理失败");
            }
        }
        List<Long> deviceIds = param.getDeviceIds();
        if (CollectionUtil.isNotEmpty(deviceIds)) {
            for (Long deviceId : deviceIds) {
                UserCollect userCollect = new UserCollect();
                BeanUtils.copyProperties(param, userCollect);
                Long id = IdGenerator.SNOW.generate();
                userCollect.setId(id);
                userCollect.setDeviceId(deviceId);

                if (!userCollectRepository.create(userCollect)) {
                    throw new RuntimeException("处理失败");
                }
            }
        }
    }

    /**
     * 移除我的收藏
     *
     * @param id
     */
    @Override
    public void removeUserCollect(Long id) {
        userCollectRepository.removeById(id);
    }

    /**
     * 启动/禁用我的收藏
     *
     * @param id
     */
    @Override
    public void enabledUserCollect(Long id) {
        UserCollect userCollect = userCollectRepository.getByIdCheck(id);
        userCollect.setIsDisable(!userCollect.getIsDisable());
        userCollectRepository.edit(userCollect);
    }

    /**
     * 切换收藏
     *
     * @param deviceId
     */
    @Override
    public void switchUserCollect(Long deviceId) {
        UserCollect collect = new UserCollect();
        collect.setDeviceId(deviceId);
        collect.setUserId(WebContext.getCurrentUserId());
        collect = userCollectRepository.getByEntity(collect);

        if (collect == null) {
            collect = new UserCollect();
            collect.setDeviceId(deviceId);
            collect.setUserId(WebContext.getCurrentUserId());
            collect.setIsDisable(false);
            collect.setIsDelete(false);
            if (!userCollectRepository.create(collect)) {
                throw new RuntimeException("处理失败");
            }
        } else {
            if (!userCollectRepository.removeById(collect.getId())) {
                throw new RuntimeException("处理失败");
            }
        }
    }


    /**
     * 获取我的收藏 列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetUserCollectListVo> getUserCollectList(GetUserCollectListParam param) {

        SelectUserCollectDto dto = new SelectUserCollectDto();
        BeanUtils.copyProperties(param, dto);
        Page<UserCollect> page = userCollectRepository.selectUserCollect(dto);
        List<UserCollect> userCollectList = page.getRecords();
        List<GetUserCollectListVo> list = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(userCollectList)) {

            List<Long> deviceIds = new ArrayList<>();
            List<Long> userIds = new ArrayList<>();

            userCollectList.forEach(v -> {
                deviceIds.add(v.getDeviceId());
                userIds.add(v.getUserId());
            });

            Map<Long, Device> deviceMap = deviceRepository.getMap(deviceIds);
            Map<Long, User> userMap = userRepository.getMap(userIds);

            for (UserCollect userCollect : userCollectList) {
                GetUserCollectListVo vo = new GetUserCollectListVo();
                BeanUtils.copyProperties(userCollect, vo);
                if (deviceMap.containsKey(userCollect.getDeviceId())) {
                    vo.setDeviceCode(deviceMap.get(userCollect.getDeviceId()).getCode());
                }
                if (userMap.containsKey(userCollect.getUserId())) {
                    vo.setUserName(userMap.get(userCollect.getUserId()).getName());
                }
                list.add(vo);
            }
        }
        return new PageResult<>(list, page);

    }

    /**
     * 获取我的收藏下拉列表
     *
     * @param param
     * @return
     */
    @Override
    public List<GetUserCollectDownListVo> getUserCollectDownList(GetUserCollectDownListParam param) {
        UserCollect po = new UserCollect();
        if (param != null) {
            BeanUtils.copyProperties(param, po);
        }
        List<UserCollect> userCollectList = userCollectRepository.getListByEntity(po);
        List<GetUserCollectDownListVo> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userCollectList)) {
            List<Long> deviceIds = new ArrayList<>();
            List<Long> userIds = new ArrayList<>();

            userCollectList.forEach(v -> {
                deviceIds.add(v.getDeviceId());
                userIds.add(v.getUserId());
            });
            Map<Long, User> userMap = userRepository.getMap(userIds);
            Map<Long, DataDictionary> areaMap = new HashMap<>();
            Map<Long, Device> deviceMap = new HashMap<>();

            List<Device> devices = deviceRepository.listByIds(deviceIds);
            if (CollectionUtil.isNotEmpty(devices)) {
                deviceMap = devices.stream().collect(Collectors.toMap(Device::getId, pojo -> pojo));
                //提取区域的id用于批量查询获取区域名称
                List<Long> areaIds = devices.stream().map(Device::getAreaId).distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(areaIds)){
                    areaMap = dataDictionaryRepository.getMap(areaIds);
                }
            }

            for (UserCollect userCollect : userCollectList) {
                GetUserCollectDownListVo vo = new GetUserCollectDownListVo();
                BeanUtils.copyProperties(userCollect, vo);
                //设备
                if (deviceMap.containsKey(userCollect.getDeviceId())) {
                    Device device = deviceMap.get(userCollect.getDeviceId());
                    vo.setDeviceCode(device.getCode());
                    //根据设备的区域获取区域名称
                    if (areaMap.containsKey(device.getAreaId())) {
                        vo.setAreaId(device.getAreaId());
                        vo.setAreaName(areaMap.get(device.getAreaId()).getName());
                    }
                }
                //获取用户名称
                if (userMap.containsKey(userCollect.getUserId())) {
                    vo.setUserName(userMap.get(userCollect.getUserId()).getName());
                }
                list.add(vo);
            }
        }
        return list;
    }


}



